package com.akino.gulimall.product.service.impl;

import com.akino.gulimall.product.service.CategoryBrandRelationService;
import com.akino.gulimall.product.vo.Catelog2Vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.akino.common.utils.PageUtils;
import com.akino.common.utils.Query;

import com.akino.gulimall.product.dao.CategoryDao;
import com.akino.gulimall.product.entity.CategoryEntity;
import com.akino.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装成父子的树形结构
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单是否被别的地方引用

        // 逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    // [2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> path = findParentPath(catelogId, paths);
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
//    @CacheEvict(value = "category",key = "'getLevel1Categories'")
//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Categories'"),
//            @CacheEvict(value = "category",key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category",allEntries = true) // 清除模式
//    @CachePut // 双写模式
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    // 代表当前方法的结果需要缓存，如果缓存中有，方法不用调用；如果缓存中没有，就调用方法，将方法的结果放入缓存
    // 每一个需要缓存的数据都来指定要放到哪个名字的缓存（缓存的分区按照业务类型分）
    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }
    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        // 查出所有1级分类
        List<CategoryEntity> level1Categories = getParent_cid(categoryEntities, 0L);
        // 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 每一级的一级分类，查到一级分类的二级分类
            List<CategoryEntity> entities = getParent_cid(categoryEntities, v.getCatId());
            // 封装上面的结果
            List<Catelog2Vo> collect = null;
            if (entities != null) {
                collect = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catalog = getParent_cid(categoryEntities, l2.getCatId());
                    if (level3Catalog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect1 = level3Catalog.stream().map(l3 -> {
                            // 封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect1);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return parent_cid;
    }
    // TODO 产生堆外内存溢出：OutOfDirectMemoryError
    // 原因：SpringBoot默认使用lettuce作为操作redis的客户端，使用netty进行网络通信
    // lettuce的bug导致netty堆外内存溢出
//    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson2(){
        /**
         * 给缓存中放JSON字符串，拿出的JSON字符串逆转为能用的对象类型（序列化与反序列化）
         * 1.设置空结果缓存，解决缓存穿透
         * 2.设置过期时间（加随机值），解决缓存雪崩
         * 3.加锁，解决缓存击穿
         */
        // 1.加入缓存逻辑（缓存中存的数据是json字符串）
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)){
            // 2.缓存中没有数据，查询数据库
            Map<String, List<Catelog2Vo>> catalogJsonFormDb = getCatalogJsonFormDbWithRedisLock();
            return catalogJsonFormDb;
        }
        // 将拿出的JSON转为指定的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});

        return result;
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithRedisLock() {
        // 占分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if (lock){
            // 加锁成功，执行业务
            // 设置过期时间（必须和加锁同步）
//            redisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> dataFromDB;
            try{
                dataFromDB = getDataFromDB();
            }finally {
                // 解锁，获取值+对比成功删除=原子操作 -> lua脚本操作
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if (uuid.equals(lockValue)){
//                // 删除自己的锁
//                redisTemplate.delete("lock");
//            }
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDB;
        } else {
            // 加锁失败
            // 休眠100ms重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFormDbWithRedisLock();  // 自旋的方式（容易栈溢出）
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        // 得到锁之后，再去缓存中确定一次，如果没有才需要继续查询
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            // 缓存不为空，直接返回
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        // 查出所有1级分类
        List<CategoryEntity> level1Categories = getParent_cid(categoryEntities, 0L);
        // 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 每一级的一级分类，查到一级分类的二级分类
            List<CategoryEntity> entities = getParent_cid(categoryEntities, v.getCatId());
            // 封装上面的结果
            List<Catelog2Vo> collect = null;
            if (entities != null) {
                collect = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catalog = getParent_cid(categoryEntities, l2.getCatId());
                    if (level3Catalog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect1 = level3Catalog.stream().map(l3 -> {
                            // 封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect1);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        // 3.将查到的数据放入缓存(将对象转为JSON放在缓存中)
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }

    // 从数据库查询并封装分类数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDbWithLocalLock() {
        /**
         * 加锁
         * 只要是同一把锁，就能锁住需要这个锁的所有线程
         * synchronized (this):SpringBoot所有组件在容器中都是单例的
         */
        // TODO 本地锁：synchronized，JUC(Lock) 在分布式情况下，想要锁住所有，必须使用分布式锁
        synchronized (this) {
            // 得到锁之后，再去缓存中确定一次，如果没有才需要继续查询
            return getDataFromDB();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntities,Long parentCid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
    }

    // [225,25,2]
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        // 收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}